<template>
  <Modal
    :title="title"
    v-model="showModal"
    width="1020"
    fullscreen
    footer-hide
  >
    <Row :gutter="16" style="display: flex;">
      <Col span="11">
        <header class="mid-header">
          <span>未分配角色</span>
        </header>
        <Table border
               ref="unallocated"
               :columns="columns"
               :data="unallocatedUserList"
               @on-selection-change="selectUnallocatedData">

        </Table>
      </Col>
      <Col span="2" style="display: flex;flex-direction: column;justify-content: center;align-self:center">
        <Button type="primary" style="min-width: 4rem;" :loading="btn_loading" @click="addRoleToUser()">选中</Button>
        <Button type="default" style="min-width: 4rem;" :loading="btn_loading" @click="deleteRoleFromUser()">撤销
        </Button>
      </Col>
      <Col span="11">
        <header class="mid-header">
          <span>已分配角色</span>
        </header>
        <Table border
               ref="allocated"
               :columns="columns"
               :data="allocatedUserList"
               @on-selection-change="selectAllocatedData">

        </Table>
      </Col>
    </Row>


    <div class="demo-drawer-footer">
    </div>
  </Modal>
</template>

<script>
  import {getUserRoleList, getNotUserRoleList} from '@/api/base-manage/userRole'
  import {saveRoleUser,deleteRoleUser} from '@/api/base-manage/roleUser'

  export default {
    name: 'allot-user',
    components: {},
    props: {
      para: {},
    },
    data() {
      return {
        showModal: false,
        title:'分配角色',
        maxTableHeight: 0,
        userData: {},
        btn_loading: false,
        userId: '',
        unallocatedUserList: [],
        allocatedUserList: [],
        selectUnallocatedUserList: [],
        selectAllocatedUserList: [],
        columns: [{
          type: 'selection',
          width: 60,
          align: 'center'
        }, {
          title: '角色名',
          key: 'role',
        }]
      }
    },
    mounted() {
      console.log('tttttt',this.modal_title);

    },
    methods: {
      getData(userId) {
        this.getTableList(userId).then(res => {
          _.forEach(res, function (v) {
            if (!v.success) {
              this.$Message.success(v.msg || '获取角色列表成功');
            }
          })
        }).catch(err => {
          console.log(err);
          this.$Message.error('获取角色列表失败');
        })
      },
      show(row) {
        console.log(row);
        this.showModal = true;
        this.userData = row;
        const {id: userId,name} = this.userData;
        this.userId = userId;
        this.title = '分配角色-'+name;
        this.getData(userId);
        this.$nextTick(() => {
          this.setMaxTableHeight()
        })
      },
      cancel() {
        this.showModal = false;
      },
      setMaxTableHeight() {
        let allocatedHeight = this.$refs.allocated.$el.clientHeight;
        let unallocatedHeight = this.$refs.unallocated.$el.clientHeight;
        this.maxTableHeight = allocatedHeight > unallocatedHeight ? allocatedHeight : unallocatedHeight;
      },
      addRoleToUser() {
        let roleUserList = [];
        const userId = this.userId;
        _.forEach(this.selectUnallocatedUserList, function (v) {
          roleUserList.push({roleId: v.id, userId: userId})
        })
        if (!roleUserList.length > 0) {
          this.$Message.success('请至少选择一个角色');
          return;
        }
        let params = {
          roleUserList: roleUserList
        }
        saveRoleUser(params).then(res => {
          if (res.data.success) {
            this.btn_loading = false;
            this.selectUnallocatedUserList = [];
            this.$Message.success(res.data.msg || '保存成功');
            return this.getTableList(userId);
          } else {
            this.btn_loading = false;
            this.$Message.error(res.data.msg || '保存失败');
          }
        }).then(res => {
          _.forEach(res, function (v) {
            if (!v.success) {
              this.$Message.success(v.msg || '获取角色列表失败');
            }
          })
        }).catch(err => {
          console.log(err);
          this.$Message.error('连接错误!');
          this.btn_loading = false;
        })
      },
      deleteRoleFromUser() {
        let roleUserList = [];
        const userId = this.userId;
        _.forEach(this.selectAllocatedUserList, function (v) {
          roleUserList.push({roleId: v.id, userId: userId})
        })
        if (!roleUserList.length > 0) {
          this.$Message.success('请至少选择一个角色');
          return;
        }
        let params = {
          roleUserList: roleUserList
        }
        deleteRoleUser(params).then(res => {
          if (res.data.success) {
            this.btn_loading = false;
            this.selectAllocatedUserList = [];
            this.$Message.success(res.data.msg || '撤销成功');
            return this.getTableList(userId);
          } else {
            this.btn_loading = false;
            this.$Message.error(res.data.msg || '撤销失败');
          }
        }).then(res => {
          _.forEach(res, function (v) {
            if (!v.success) {
              this.$Message.success(v.msg || '获取角色列表失败');
            }
          })
        }).catch(err => {
          console.log(err);
          this.$Message.error('连接错误!');
          this.btn_loading = false;
        })
      },
      selectUnallocatedData(list) {
        //选择用户未分配的角色
        this.selectUnallocatedUserList = list
      },
      selectAllocatedData(list) {
        //选择用户已分配的角色
        this.selectAllocatedUserList = list
      },

      getTableList(userId) {
        const getRoleUserPromise = getUserRoleList({userId: userId}).then(res => {
          //获取用户已分配的角色
          this.allocatedUserList = res.data;
          return {
            success: true,
            msg: '获取用户已分配的角色列表成功'
          }
        }).catch(err => {
          return {
            success: false,
            msg: '获取用户已分配的角色列表失败'
          }
        });
        const getNotRoleUserPromise = getNotUserRoleList({userId: userId}).then(res => {
          //获取用户未分配的角色
          this.unallocatedUserList = res.data;
          return {
            success: true,
            msg: '获取用户未分配的角色列表成功'
          }
        }).catch(err => {
          console.log(res);

          return {
            success: false,
            msg: '获取用户未分配的角色列表失败'
          }
        });
        //当promise数组都写catch语法时，数组的每个元素必定会有结束状态resolve——正确的、异常的。
        //所以all被then语法糖包裹时，一定只能进then语法，而不会进后续的catch语法，所以需要在后面的then中判断数组的每个返回值。
        return Promise.all([
          getRoleUserPromise,
          getNotRoleUserPromise
        ])
      }
    },
    watch: {},
    computed: {}
  }
</script>

<style scoped>
.mid-header{
  font-weight: 500;
  margin: 30px 0 10px;
  position: relative;
}
  .mid-header:before{
    content: "";
    display: block;
    width: 100%;
    height: 1px;
    background: #eee;
    position: absolute;
    top: 10px;
    left: 0;
  }
  .mid-header span{
    display: inline-block;
    background: #fff;
    padding: 0 5px 0 18px;
    position: relative;
    margin-left: 30px;
    font-size: 14px;
  }
</style>
